//
//  JEHMineViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/1.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHMineViewController.h"

@interface JEHMineViewController ()<UITableViewDataSource, UITableViewDelegate, buttonClickSkip>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSArray *leftNameArray;
@property (nonatomic, copy) NSString *cachesPath;
@property (nonatomic, copy) NSString *userName;

@end

@implementation JEHMineViewController

@synthesize cachesPath = _cachesPath;

#pragma mark - memoryManagement
- (void)dealloc {
    
    [_leftNameArray release];
    [_tableView release];
    [_cachesPath release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSIndexPath *index = [NSIndexPath indexPathForRow:2 inSection:1];
    [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTableView];
    [self setLeftNameArray];
}

#pragma mark - leftNameArray
- (void)setLeftNameArray {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    self.leftNameArray = @[@"恢复数据", @"夜间模式", @"清除缓存"];
}

#pragma mark - createTableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.width, self.view.height - 44 - 20) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [_tableView nightMode];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.backgroundColor = [UIColor lightGrayColor];
    [_tableView registerClass:[JEHMineFirstTableViewCell class] forCellReuseIdentifier:@"JEHMineFirstTableViewCellIdentifier"];
    [_tableView registerClass:[JEHSecondTableViewCell class] forCellReuseIdentifier:@"JEHSecondTableViewCellIdentifier"];
    [self.view addSubview:_tableView];
}

#pragma mark - UITableViewDelegateMethod
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return 1;
    } else {

        return self.leftNameArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        JEHMineFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHMineFirstTableViewCellIdentifier"];
        cell.delegate = self;
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if ([userDefaults objectForKey:@"login"] == nil) {
            
            cell.userLabel.text = @"登陆账号";
            cell.userPicture.image = [UIImage imageNamed:@"userPicture"];
        } else {
            JEHDataBaseHandle *handle = [JEHDataBaseHandle shareDataBaseHandle];
            [handle openDataBase];
            [handle selectUserLoginAllFromDataBase];
            cell.userLabel.text = [handle.nameArray.copy firstObject];
            [cell.userPicture sd_setImageWithURL:[NSURL URLWithString:[handle.urlArray.copy firstObject]]];
            [handle closeDataBase];
        }
        return cell;
    } else {
        JEHSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHSecondTableViewCellIdentifier"];
        if (indexPath.section == 1) {
            
            cell.leftLabel.text = self.leftNameArray[indexPath.row];
            if (indexPath.row == 1) {
                
                cell.rightLabel.alpha = 0;
                cell.switches.userInteractionEnabled = NO;
                cell.tag = 1001;
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"NightMode"] isEqualToString:@"Night"]) {
                    
                    cell.switches.on = YES;
                } else {
                    cell.switches.on = NO;
                }
            } else {
                cell.switches.alpha = 0;
                cell.switches.userInteractionEnabled = NO;
                cell.leftLabel.text = self.leftNameArray[indexPath.row];
                if (indexPath.row == 2) {
                    
                    cell.rightLabel.text = [NSString stringWithFormat:@"%.1fM", [self getCaches]];
                }
            }
        }
        [cell.leftLabel nightMode];
        [cell.rightLabel nightMode];
        [cell nightMode];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 4) {
        
        return CGFLOAT_MIN;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return 200;
    } else {
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
#pragma mark - SinaWeiBoDesign
    if (indexPath.section == 0) {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        JEHDataBaseHandle *handle = [JEHDataBaseHandle shareDataBaseHandle];
        [handle openDataBase];
        if ([user objectForKey:@"login"] == nil) {
            
            [UMSocialData setAppKey:@"566fbfa9e0f55a1273002780"];
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
            snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
                
                //          获取微博用户名、uid、token等
                if (response.responseCode == UMSResponseCodeSuccess) {
                    
                    [user setObject:@"YES" forKey:@"login"];
                    UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                    [handle insertUserLoginIntoDataBase:snsAccount.userName withUrl:snsAccount.iconURL];
                    self.userName = snsAccount.userName;
                    [self.tableView reloadData];
                    //                    NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                }});
        } else {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定退出当前账号？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:nil forKey:@"login"];
                [self.tableView reloadData];
            }];
            UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:actionYes];
            [alertController addAction:actionNo];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            [handle deleteUserLoginFromDataBase:self.userName];
            [self.tableView reloadData];
        }
        [handle closeDataBase];
    }
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你确定？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSArray *nameArray = @[@"推荐", @"娱乐", @"体育", @"财经", @"汽车", @"科技", @"搞笑", @"辽宁"];
                NSArray *urlArray = @[kRecommendGETURL, kEntertainmentGETURL, kSportsGETURL, kFinanceGETURL, kAutomobilesGETURL, kTechnologyGETURL, kFunnyGETURL, kLiaoningGETURL];
                JEHDataBaseHandle *handle = [JEHDataBaseHandle shareDataBaseHandle];
                [handle openDataBase];
                for (int i = 0; i < nameArray.count; i++) {
                    
                    if (![handle selectWithName:nameArray[i]]) {
                        
                        [handle insertTitleArrayIntoDataBase:nameArray[i] withUrl:urlArray[i]];
                    }
                }
                [handle closeDataBase];
                NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                [center postNotificationName:@"ReloadData" object:nil];
            }];
            [alertController addAction:actionYes];
            [alertController addAction:actionNo];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
        if (indexPath.row == 1) {
            
            JEHSecondTableViewCell *cell = (JEHSecondTableViewCell *)[self.view viewWithTag:1001];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            if ([[user objectForKey:@"NightMode"] isEqualToString:@"Night"]) {
                
                cell.switches.on = NO;
                self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
                [user setObject:@"Day" forKey:@"NightMode"];
                self.tableView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:234 / 255.0 alpha:1];
                [self.tableView reloadData];
            } else {
                cell.switches.on = YES;
                self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
                [user setObject:@"Night" forKey:@"NightMode"];
                self.tableView.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
                [self.tableView reloadData];
            }
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"ReloadData" object:nil];
        }
        if (indexPath.row == 2) {
            
            [self clearCaches];
            NSIndexPath *index = [NSIndexPath indexPathForRow:2 inSection:1];
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本次共清除缓存" message:[NSString stringWithFormat:@"%.1fM", [self getCaches]] delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alert show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [alert dismissWithClickedButtonIndex:0 animated:NO];
            });
            [alert release];
        }
    }
}

#pragma mark - buttonClickSkip
- (void)passButtonTag:(NSInteger)tag {
    
    if (tag == 100) {
        
        JEHCollectionViewController *collection = [[JEHCollectionViewController alloc] init];
        [self presentViewController:collection animated:YES completion:^{
            
        }];
        [collection release];
    } else if (tag == 101) {
        
    } else {
        
    }
}

#warning 清除缓存功能
#pragma mark - getCaches
- (float)getCaches {
    
    NSString *path =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    return [self folderSizeAtPath:path];
}

#pragma mark - clearCaches
- (void)clearCaches {
    
    //获取完整路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameAarray = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameAarray) {
            //拼接绝对路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            
            //通过文件管理者删除文件
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
}

#pragma mark - fileSizeAtPath
- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil]fileSize];
    }
    return 0;
}

#pragma mark - folderSizeAtPath
- (float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    //根据路径获取文件夹里面元素集合
    //获取集合类型的枚举类型
    NSEnumerator *enumeratot = [[manager subpathsAtPath:path] objectEnumerator];
    //每次遍历得到的文件名
    //文件夹的大小
    NSString *fileName = [NSString string];
    float folderSize = 0;
    while ((fileName = [enumeratot nextObject])!= nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    return folderSize/(1024*1024.0);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
